//
//  StartViewController.swift
//  socksTest
//
//  Created by liujianlong on 2023/6/21.
//

import UIKit
import TCCKit
import CoreBluetooth
class StartViewController: EPViewController {
    var array = [CBPeripheral]()
    let timerManager = MMTimer()
    var control_title = "单独控制"
    var time = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
    }
    
    override func initUI() {
        title = LS("测试")
        backBtn?.isHidden = true
        tableViewStyle = .grouped
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableHeaderView = UIView(frame: .zero)
        tableView.mj_header = nil
        tableView.mj_footer = nil
        tableView.register(StartDataCell.nib(), forCellReuseIdentifier: StartDataCell.ID() + "0")
        tableView.register(StartDataCell.nib(), forCellReuseIdentifier: StartDataCell.ID() + "1")
        tableView.register(StartBottomCell.nib(), forCellReuseIdentifier: StartBottomCell.ID())
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(20)
            make.top.bottom.equalToSuperview().inset(0)
        }
        array = BLE.connectedPeripherals
        _ = array.compactMap{
            $0.model.off_time = 0
            $0.model.change = .normal
            BLEData.checkStatus.write($0)
            BLEData.motorTime(0).write($0)
        }
    }
    
    
    func action(_ sender: String, _ data:Any , _ index:Int){
        
        guard BLE.connectedPeripherals.count > index, let per = BLE.connectedPeripherals[index] as? CBPeripheral else{return}
        let array = control_title == "合并控制" || sender == "结束测试" || sender == "震动测试" ? BLE.connectedPeripherals : [per]
        
        switch sender{
        case "单独控制",
            "合并控制":
            control_title = sender
        case "结束测试":
            self.alert(LS("提示"), LS("结束测试，袜子即将关机，确定结束测试吗")) {} _: {
                _ = array.compactMap{
                    $0.model.off_time = 0
                    $0.model.change = .normal
                    $0.model.ison = false
                    BLEData.On_off(false).write($0)}
                DispatchQueue.main.asyncAfter(deadline: .now() + 1){
                    self.navigationController?.popToRootViewController(animated: true)
                }
            }
        case "震动测试":
            guard let on = data as? Bool else{return}
            _ = array.compactMap{
                $0.model.motor = on
                BLEData.motorOn_off(on).write($0)}
            if on && time < 10 {
                timerManager.startTimer(interval: .seconds(2)) {[weak self] in
                    self?.time += 2
                    self?.action("震动测试", true , index)
                }
            }else{
                time = 0
                timerManager.stopTimer()
            }
        case "设置温度_按钮",
            "设置温度_滑动":
            guard let temp = data as? Int else {return}
            _ = array.compactMap{
                if $0.model.ison{
                    $0.model.targetValue = temp///设置温度的目标温度
                    $0.model.change = sender.hasSuffix("按钮") ? .btn : .slider
                    BLEData.setupTemp(temp).write($0)}}
        case "开关机":
            guard let on = data as? Bool else{return}
            _ = array.compactMap{
                $0.model.off_time = 0
                $0.model.change = .normal
                $0.model.ison = on
                BLEData.On_off(on).write($0)}
        case "选择时长":
            guard let min = data as? Int else{return}
            _ = array.compactMap{
                if $0.model.ison{
                    $0.model.off_time = min
                    BLEData.motorTime(min).write($0)}}
        default:
            break
        }
        tableView.reloadData()
    }
    
    
}
//MARK: - 蓝牙相关通知
extension StartViewController{
    override func addNotify() {
        NotifyTool.add(self, #selector(actionForBLESDataUpdate), BLEData.dataupdate.ack)
        NotifyTool.add(self, #selector(actionForBLEStatus), BLEStatusUpdateNotifyName)
        NotifyTool.add(self, #selector(actionForSetupTemp), BLEData.setupTemp(0).ack)
    }
    
    @objc func actionForBLEStatus(){
        array = BLE.connectedPeripherals
        _ = array.compactMap{ BLEData.checkStatus.write($0)}
        tableView.reloadData()
    }
    
    @objc func actionForBLESDataUpdate(_ notify:Notification){
        array = BLE.connectedPeripherals
        tableView.reloadData()
    }
    
    @objc func actionForSetupTemp(_ notify:Notification){
        tableView.reloadData()
    }
}

//MARK: - UITableViewDataSource
extension StartViewController : UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
       // return control_title == "单独控制" ? array.count + 1 : 2
        return array.count + 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == array.count{
            let cell = tableView.dequeueReusableCell(withIdentifier: StartBottomCell.ID()) as! StartBottomCell
            cell.switchBtn.isOn = timerManager.isRunning
            cell.block = {[weak self] title in
                self?.action(title, "" , 0)
            }
            cell.switchBlock = {[weak self] on in
                self?.action("震动测试", on, 0)
            }
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: StartDataCell.ID() + "\(indexPath.section)", for: indexPath) as! StartDataCell
        cell.peripheral = array[indexPath.section]
        cell.config()
        cell.block = {[weak self] title,data in
            self?.action(title, data, indexPath.section)
        }
        return cell
    }
    
    
}
//MARK: - UITableViewDelegate
extension StartViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}

